/**
 * @author   zhangyp
 * @created  2013-8-12 下午1:18:44
 * @email    zviolet@163.com
 * TODO      app 版本自动更新
 */
package com.bible.fire.local;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.dom4j.DocumentHelper;

import com.bible.fire.util.AndroidUtil;
import com.bible.fire.util.SystemConstant;
import com.bible.fire.util.XMLUtil;
import com.bible.fire.util.http.HttpClientHelper;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;


public class VersionManager {
	
	private static String TAG = VersionManager.class.getSimpleName();
	
	/**
	 * 获得最新的版本信息
	 */
	public static void checkLatestVersion( Context context, ProgressDialog pd){
		String url = ConfigManager.getLastestVersionUrl();
		pd.show();
		final Context fcontext = context;
		final ProgressDialog fpd = pd;
		Handler handler = new Handler(){
			@Override
			 public void handleMessage(Message m){
				if( m.what == 1 ){
					 //成功
					 String data = m.getData().getString("result");
					 if( data != null ){
						 try {
							 Map<String, Object> map = XMLUtil.Dom2Map( DocumentHelper.parseText( data ) );
							 Double version = Double.parseDouble( String.valueOf(map.get("version")) );
							 String apkUrl = String.valueOf(map.get("url"));
							 AndroidUtil.setAttribute("latest_version", version);
							 AndroidUtil.setAttribute("apk_url", apkUrl);
							 Log.d(TAG, "latest_version : " + version + ",url : " + apkUrl );
							 fpd.dismiss();
							 promptVersion( fcontext );
						} catch (Exception e) {
							Log.e(TAG, "parse xml error...", e);
						} finally{
							fpd.dismiss();
						}
					 }
				}else if( m.what == 0 ){
					//失败
					String data = m.getData().getString("error");
					Log.i("handle error", data);
					fpd.dismiss();
				}
			}
		};
		boolean isSuccess = HttpClientHelper.sendHttpRequest( url, null, handler, 3000, 1000 );
		if( !isSuccess ){
			Log.d(TAG, "get latest version failed");
			fpd.dismiss();
		}
	}
	
	
	public static void promptVersion( Context context ){
		Double latestVersion = (Double)AndroidUtil.getAttribute("latest_version");
		if( latestVersion == null ){
			return;
		}
		String versionName = AndroidUtil.getVersion();
		if( versionName == null || versionName.length() == 0 ){
			return;
		}
		AndroidUtil.removeAttribute("latest_version");
		Double currentVersion = Double.parseDouble( versionName );
		if( latestVersion > currentVersion ){
			AlertDialog.Builder builer = new Builder( context ) ;     
		    builer.setTitle("版本升级");    
		    builer.setMessage("检测到最新版本，请及时更新!");    
		    //当点确定按钮时从服务器上下载 新的apk 然后安装      
		    final Context fcontext = context;
		    builer.setPositiveButton("确定", new OnClickListener() {    
		    public void onClick(DialogInterface dialog, int which) {    
		            Log.d(TAG,"下载apk,更新");
		            dialog.dismiss();
		            downLoadApk( fcontext );    
		        }       
		    });    
		    //当点取消按钮时进行登录     
		    builer.setNegativeButton("取消", new OnClickListener() {    
		        public void onClick(DialogInterface dialog, int which) {     
		        	dialog.dismiss();
		        }    
		    });    
		    AlertDialog dialog = builer.create();    
		    dialog.show();
		}
	}
	
	public static void downLoadApk( Context context){
		final Context fcontext = context;
		final ProgressDialog pd = new ProgressDialog( fcontext ); 
		AsyncTask<Object, Object, File> downloadTask = new AsyncTask<Object, Object, File>(){
			 			
		   @Override  
	       protected void onPreExecute(){  
	           //第一个执行方法  
	           Log.d(TAG, "开始执行");
	           super.onPreExecute(); 
	           //进度条对话框        
			   pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			   pd.setCancelable( false );
			   pd.setMessage("正在下载更新");    
			   pd.show();
	       }  

			@Override
			protected File doInBackground(Object... params) {
				// TODO Auto-generated method stub
				String path = ConfigManager.getServerUrl() + (String)AndroidUtil.getAttribute("apk_url");
				File file = getFileFromServer( path, pd );
				pd.dismiss();
				return  file; 
			}
			
		    @Override  
	        protected void onPostExecute(File result) {  
	           //doInBackground返回时触发，换句话说，就是doInBackground执行完后触发  
	           //这里的result就是上面doInBackground执行后的返回值 
	           Log.d(TAG, "下载文件完成");	                 	           
	           super.onPostExecute(result);
	           if( result != null ){
	        	   installApk( result, fcontext );
	           }else{
	        	   Toast.makeText(fcontext, "下载更新文件失败!", Toast.LENGTH_LONG).show();
	           }	           
	        }  

		};
		downloadTask.execute();
	}
	
	public static File getFileFromServer(String path, ProgressDialog pd){
		try {
			URL url = new URL(path);     
	        HttpURLConnection conn =  (HttpURLConnection) url.openConnection();     
	        conn.setConnectTimeout(10000);     
	        //获取到文件的大小       
	        pd.setMax(conn.getContentLength());     
	        InputStream is = conn.getInputStream();     
	        File file = new File(SystemConstant.FILE_DOWNLOAD_PATH, "3fire.apk");     
	        FileOutputStream fos = new FileOutputStream(file);     
	        BufferedInputStream bis = new BufferedInputStream(is);     
	        byte[] buffer = new byte[1024];     
	        int len ;     
	        int total=0;     
	        while((len =bis.read(buffer))!=-1){     
	            fos.write(buffer, 0, len);     
	            total+= len;     
	            //获取当前下载量      
	            pd.setProgress(total);     
	        }     
	        fos.close();     
	        bis.close();     
	        is.close();     
	        return file;
		}catch(Exception e) {
			Log.e(TAG, "download apk error", e );
		}
		return null;
	}    
	
	public static void installApk( File file, Context context ){
		Intent intent = new Intent();    
	    //执行动作     
	    intent.setAction(Intent.ACTION_VIEW);    
	    //执行的数据类型     
	    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
	    context.startActivity(intent);
	}

}
